import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { getToken } from 'next-auth/jwt'

// This function can be marked `async` if using `await` inside
export async function middleware(request: NextRequest) {
  // 允许API和静态资源访问
  if (
    request.nextUrl.pathname.startsWith('/api') ||
    request.nextUrl.pathname.startsWith('/_next') ||
    request.nextUrl.pathname === '/' ||
    request.nextUrl.pathname === '/sign-in' ||
    request.nextUrl.pathname === '/sign-up'
  ) {
    return NextResponse.next()
  }
  
  // 检查用户是否已登录
  const token = await getToken({ 
    req: request,
    secret: process.env.AUTH_SECRET
  })
  
  // 如果用户未登录，重定向到登录页面
  if (!token) {
    return NextResponse.redirect(new URL('/sign-in', request.url))
  }
  
  // 用户已登录，允许访问
  return NextResponse.next()
}
 
// See "Matching Paths" below to learn more
export const config = {
  matcher: [
    /*
     * 匹配所有路径，但排除以下路径：
     * - 静态资源 (_next/static, favicon.ico 等)
     */
    '/((?!_next/static|_next/image|favicon.ico).*)',
  ],
}